#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''eof
name:3年内企业征信强制执行校验
code:EntCredit_Enforce_3Yr
tableName:
columnName:
groups:准入>企业征信校验
dependencies:IC_DSJ_2D
type:常用指标
dataSourceType:在线指标
description:
eof'''

'''
缺少时间样例：%Y%m%d or %Y-%m-%d
ECRForceExecution：强制执行记录
Caseregistrationdate:立案日期
'''

import sys
import pandas as pd
import datetime
import re
import json

reload(sys)
sys.setdefaultencoding('utf-8')

#标准化时间格式
def Formate(time):
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date
    # tmp = r.sub('', time)
    # if tmp.isdigit() and len(tmp) >= 8:
    #     return tmp[0:8]
    # elif tmp.isdigit() and len(tmp) > 0 and len(tmp) < 8:
    #     date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
    #     return date
    # else:
    #     return None


last_year_list = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset(years=i)).strftime('%Y%m%d')\
                    for i in [3 , 0]]

# print last_year_list
def EntCredit_Enforce_3Yr():
    null_type_list = ['', None, 'null', 'Null', 'NULL',' /','--','-']
    count = []
    try:
        if EC in null_type_list:
            return u'缺失值'
        if len(EC) == 0:
            return u'缺失值'
        ecr = json.loads(EC[0]["ecr"])
        if ecr in null_type_list:
            return u'缺失值'
        if len(ecr) == 0:
            return u'缺失值'
        if ecr.has_key('ECRForceExecution') and ecr['ECRForceExecution'] not in null_type_list:
            for i in ecr['ECRForceExecution']:
                if i.has_key('Caseregistrationdate') and i['Caseregistrationdate'] not in null_type_list :
                    try:
                        if last_year_list[0]<Formate(i['Caseregistrationdate'])<= last_year_list[1]:
                            count.append(float(1))
                            # print Formate(i['Caseregistrationdate'])
                        else:
                            count.append(float(0))
                    except:
                            count.append(None)
                else:
                    count.append(None)
        else:
            return u'缺失值'
        #若count均为None,则返回缺失值,否则将None置为0
        enforce_count = filter(lambda x: x is not None, count)
        return sum(enforce_count) if len(enforce_count) != 0 else u'缺失值'
    except:
        return u'缺失值'

result = EntCredit_Enforce_3Yr()